package com.laizhenghua.hystrix.service.impl;

import com.laizhenghua.hystrix.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @date: 2022/2/14 20:20
 */
@Slf4j
@Service(value = "paymentService")
public class PaymentServiceImpl implements PaymentService {
    @Override
    @HystrixCommand(fallbackMethod = "paymentServiceTimeoutHandler", commandProperties = {
            // 3s以内走正常业务方法，超过3s走fallback
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public Map<String, Object> testError() {
        Map<String, Object> data = new HashMap<>();
        data.put("threadName", Thread.currentThread().getName());
        data.put("methodName", "testError");
        try {
            Thread.sleep(5000); // 5s
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        // int a = 10 / 0; // 注意此行代码
        log.info("method [testError] is running");
        return data;
    }

    public Map<String, Object> paymentServiceTimeoutHandler() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "系统正在努力运行，请稍等...");
        return result;
    }
}
